import {getToken, removeToken, setToken} from "@/utils/auth";
import {getUser, loginApi} from "@/api/user";
import Cookies from "js-cookie";
import {getSign} from "@/api/im";
import Vue from "vue";
const state={
    token: getToken(),
    user:Cookies.get('user'),
    identity:Cookies.get('identity'),
    IMReady: false
}
const mutations={
    SET_TOKEN(state,token){
        if(token===null){
            removeToken();
        }else{
            setToken(token.toString())
        }
        state.token=token;
    },
    SET_USER(state,user){
        if(user===null){
            Cookies.remove('user');
        }else{
            Cookies.set('user',JSON.stringify(user))
        }
        state.user=user
    },
    SET_IDENTITY(state,identity){
        identity=identity.toString();
        Cookies.set('identity',identity)
        state.identity=identity
    },
    SET_READY: (state, ready) => {
        state.IMReady = ready
    },
}
const actions={
    login({commit}, form) {
        return new Promise((resolve, reject) => {
            loginApi(form).then((res)=>{
               if(res===405)
               {
                   resolve('验证码错误！');
               }else if(res===406)
               {
                   resolve('手机号或密码错误！');
               }else{
                   commit('SET_TOKEN',res.token);
                   commit('SET_USER',res.user);
                   commit('SET_IDENTITY',form.type);
                   resolve();
               }
            }).catch(()=>{
                reject();
            })
        })
    },
    getUser({commit}){
        return new Promise((resolve, reject) => {
            getUser({type:Cookies.get('identity')}).then((res)=>{
                commit('SET_USER',res);
                Vue.prototype.tim.updateMyProfile({
                    nick: res.realName, avatar: res.faceUrl
                })
                resolve(res);
            }).catch(()=>{
                reject();
            })
        })
    },
    loginIM({commit}){
        return new Promise((resolve, reject)=>{
            const user=typeof state.user==='object'?state.user:JSON.parse(state.user);
            const identity=state.identity;
            const prefix=identity==='1'?'dhs_personal':'dhs_enterprise';
            const userId=prefix+'_'+user.mobile;
            let userName = user.realName
            getSign({userId:userId}).then((res)=>{
                const userSig=res.userSig;
                Vue.prototype.tim.login({userID:userId,userSig}).then(()=>{
                    resolve('登录成功');
                }).catch(()=>{
                    reject('IM登录失败');
                })
            }).catch(()=>{
                reject('IM登录失败');
            })
        })
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}
